package com.cheer.ba.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.smileyloadingview.SmileyHeaderView;
import com.cheer.ba.R;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.listener.OnItemClickListener;
import com.cheer.ba.model.MyAddressModel;
import com.cheer.ba.presenter.impl.MyAddressPresenter;
import com.cheer.ba.view.adapter.FrequentlyAreaAdp;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.lib_recycle_swipe.Closeable;
import com.cheer.lib_recycle_swipe.OnSwipeMenuItemClickListener;
import com.cheer.lib_recycle_swipe.SwipeMenu;
import com.cheer.lib_recycle_swipe.SwipeMenuCreator;
import com.cheer.lib_recycle_swipe.SwipeMenuItem;
import com.cheer.lib_recycle_swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 描述 ： 我的常用地址列表
 * 作者 ：hq
 * 时间 ：2017/5/23 17:48
 */
public class FrequentlyAreasAty extends BaseCommAty {

    //没有地址
    @BindView(R.id.id_no_address_txt)
    TextView mTxtNoData;

    @BindView(R.id.id_address_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_address_recyclev)
    SwipeMenuRecyclerView mRecycleView;
    private FrequentlyAreaAdp mAdapter;
    //  存储我的地址
    private List<MyAddressModel> mSaveAddress = new ArrayList<MyAddressModel>();

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_frequen_area, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return !mSaveAddress.isEmpty();
    }

    @Override
    public void initPresenter() {
        presenter = new MyAddressPresenter();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.frequently_use_address));
        setTitleIcon(R.drawable.ic_add_oil_card, false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加常用地址
                showActivity(aty, FrequentlyAddressAty.class);
            }
        });
        setXRefreshView(mXRefreshView, true, false, false, false, new SmileyHeaderView(aty), null);
        mRecycleView.setLayoutManager(new LinearLayoutManager(aty));
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        // 设置菜单创建器。
        mRecycleView.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        mRecycleView.setSwipeMenuItemClickListener(menuItemClickListener);
        mRecycleView.smoothOpenRightMenu(0);

        mAdapter = new FrequentlyAreaAdp(mSaveAddress);
        mAdapter.setOnItemClickListener(onItemClickListener);
        mRecycleView.setAdapter(mAdapter);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        loadData(!hasDataInPage());
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false);
            }
        });
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            MyAddressModel model = (MyAddressModel) mAdapter.getItem(position);
            if (null != model) {
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.CHOOSE_MY_ADDRESS;
                event.model = model;
                EventBus.getDefault().post(event);
                finish();
            }
        }
    };

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int size = getResources().getDimensionPixelSize(R.dimen.item_height);
            if (viewType == FrequentlyAreaAdp.VIEW_TYPE_NONE) {
                //不添加滑动
            } else {
                SwipeMenuItem addItem = new SwipeMenuItem(aty)
                        .setBackgroundDrawable(getResources().getDrawable(R.color.color_c9c9c9))
//                .setImage(R.drawable.ic_home_msg)
                        .setText("设置默认")
                        .setTextColor(Color.WHITE)
                        .setTextSize(16)
                        .setHeight(size)
                        .setWidth(size);

                SwipeMenuItem addItem2 = new SwipeMenuItem(aty)
                        .setBackgroundDrawable(getResources().getDrawable(R.color.color_ff9e02))
//                .setImage(R.drawable.ic_home_msg)
                        .setText("编辑")
                        .setTextColor(Color.WHITE)
                        .setTextSize(16)
                        .setHeight(size)
                        .setWidth(size);


                SwipeMenuItem addItem3 = new SwipeMenuItem(aty)
                        .setBackgroundDrawable(getResources().getDrawable(R.color.color_ff3b32))
//                .setImage(R.drawable.ic_home_msg)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setTextSize(16)
                        .setHeight(size)
                        .setWidth(size);

                swipeRightMenu.addMenuItem(addItem);
                swipeRightMenu.addMenuItem(addItem2);
                swipeRightMenu.addMenuItem(addItem3);
            }
        }
    };

    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView#RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            // 关闭被点击的菜单。
            closeable.smoothCloseMenu();
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                MyAddressModel model = (MyAddressModel) mAdapter.getItem(adapterPosition);
                //右侧菜单
                if (menuPosition == 1) {
                    //编辑
                    Intent address = new Intent(aty, FrequentlyAddressAty.class);
                    address.putExtra(IntentKey.General.KEY_MODEL, model);
                    showActivity(aty, address);
                } else if (menuPosition == 0) {
                    //设置默认
                    ((MyAddressPresenter) presenter).defaultMyAddress(model.getUid());
                } else {
                    //删除
                    ((MyAddressPresenter) presenter).delMyAddress(model.getUid());
                }
            }
        }
    };

    /**
     * 加载数据
     *
     * @param isShowLoad
     */
    public void loadData(boolean isShowLoad) {
        ((MyAddressPresenter) presenter).getMyAddressList(isShowLoad);
        stopRefresh(mXRefreshView, 3000);
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(ConstantTag.DEL_SUCCESS, tag) || TextUtils.equals(ConstantTag.DEFAULT_SUCCESS, tag)) {
                mXRefreshView.startRefresh();
            } else if (TextUtils.equals(ConstantTag.GET_LIST_SUCCESS, tag)) {
                stopRefresh(mXRefreshView, 2000);
                //获得我的地址
                List<MyAddressModel> address = (List<MyAddressModel>) t;
                if (address.isEmpty()) {
                    mTxtNoData.setVisibility(View.VISIBLE);
                    mRecycleView.setVisibility(View.GONE);
                    mTxtNoData.setText("还没有地址，点击右上角按钮去添加吧");
                    BaseEvent event = new BaseEvent();
                    event.type = ConstantTag.NO_ADDRESS;
                    EventBus.getDefault().post(event);
                } else {
                    mTxtNoData.setVisibility(View.GONE);
                    mRecycleView.setVisibility(View.VISIBLE);
                    mSaveAddress.clear();
                    mSaveAddress.addAll(address);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void handlerByPage(int flag1, int flag2) {
        mRecycleView.setVisibility(View.GONE);
        mTxtNoData.setVisibility(View.VISIBLE);
        if (flag2 == CodeStatus.Gegeneral.ERROR_NET) {
            mTxtNoData.setText(getString(R.string.no_net_work));
        } else if (flag2 == CodeStatus.Gegeneral.ERROR_DATA) {
            mTxtNoData.setText("数据加载失败，请检查网络是否链接");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        if (TextUtils.equals(event.type, ConstantTag.DEL_SUCCESS)) {
            //刷新列表
            mXRefreshView.startRefresh();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
